<script setup>
import {ref, reactive, onMounted, computed, watch} from 'vue'
import {ElMessage, ElMessageBox, ElNotification} from 'element-plus'
import {useUserStore} from '@/stores/userStore'
import {
  User,
  Lock,
  Iphone,
  Document,
  Check,
  Close,
  Warning
} from '@element-plus/icons-vue'

const userStore = useUserStore();

// 用户信息
const userInfo = reactive({
  userId: null,
  name: '',
  avatar: '',
  phone: '',
  email: '',
  userType: '',
  authStatus: 0, // 0: 未认证, 1: 审核中, 2: 已认证, 3:认证失败
  authInfo: {
    realName: '',
    idCard: ''
  }
})


// 组件状态
const activeTab = ref('profile')
const pendingList = computed(() => userStore.authPendingList)
const isCounting = ref(false) // 验证码倒计时状态
const countdown = ref(60) // 倒计时秒数
let countdownTimer = null // 倒计时定时器

// 表单数据
const userForm = reactive({
  name: userInfo.name,
  email: userInfo.email
})
// 在初始化 userForm 后添加
watch(() => userInfo.name, (newName) => {
  if (newName) userForm.name = newName
})

watch(() => userInfo.email, (newEmail) => {
  if (newEmail) userForm.email = newEmail
})


const phoneForm = reactive({
  phone: '',
  code: ''
})

const passwordForm = reactive({
  oldPassword: '',
  newPassword: ''
})

const authForm = reactive({
  realName: '',
  idCard: '',
  agreement: false
})

const verifyForm = reactive({
  userId: null,
  status: 0,
  rejectReason: ''
})

const passwordRules = {
  oldPassword: [
    {required: true, message: '请输入原密码', trigger: 'blur'}
  ],
  newPassword: [
    {required: true, message: '请输入新密码', trigger: 'blur'},
    {min: 3, message: '密码长度至少3位', trigger: 'blur'}
  ]
}

const authRules = {
  realName: [
    {required: true, message: '请输入真实姓名', trigger: 'blur'}
  ],
  idCard: [
    {required: true, message: '请输入身份证号', trigger: 'blur'},
    {
      pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
      message: '请输入正确的身份证号',
      trigger: 'blur'
    }
  ]
}

// 初始化加载数据
onMounted(() => {
  fetchUserProfile()
  fetchAuthStatus()
  userStore.getAuthPendingList();

  if (userInfo.userType === 'ADMIN') {
    fetchPendingList()
  }
})


const fetchUserProfile = async () => {
  // 调用API/user/profile获取用户信息
  try {
    await userStore.getUserProfile();
    Object.assign(userInfo, userStore.userProfile)
    console.log("userinfo:",userInfo)

  } catch (error) {
    console.log('获取用户信息失败:', error);
    ElMessage.error('获取用户信息失败')
  }
}

const fetchAuthStatus = async () => {
  // 调用API/user/auth-status获取认证状态
  try {
    await userStore.getAuthStatus();
    userInfo.authStatus = userStore.authStatus.authStatus;
    userInfo.authInfo.realName = userStore.authStatus.realName;
    userInfo.authInfo.idCard = userStore.authStatus.idCard;
    console.log('userInfo',userInfo)

  } catch (error) {
    ElMessage.error('获取认证状态失败')
  }
}

const fetchPendingList = async () => {
  // 调用API/admin/user/auth-pending-list获取待审列表
  pendingList.value = userStore.authPendingList;
}

// 获取验证码
const handleGetVerificationCode = async () => {
  if (!phoneForm.phone) {
    ElMessage.warning('请输入新手机号')
    return
  }

  // 验证手机号格式
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(phoneForm.phone)) {
    ElMessage.error('请输入正确的手机号格式')
    return
  }

  try {
    userStore.getSsmCode(phoneForm.phone)

    // 开始倒计时
    startCountdown()
    simulateSmsNotification();
    ElMessage.success('验证码已发送，请注意查收')
  } catch (error) {
    ElMessage.error('验证码发送失败，请稍后重试')
  }
}

// 开始倒计时
const startCountdown = () => {
  isCounting.value = true
  countdown.value = 60

  countdownTimer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      stopCountdown()
    }
  }, 1000)
}

// 停止倒计时
const stopCountdown = () => {
  isCounting.value = false
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
  }
}

/* 表单提交处理 */
const handleUpdateProfile = async () => {
  // 调用API/user/profile更新信息
  try {
    userStore.updateUserProfile(userForm)
    userInfo.name = userForm.name
    userInfo.email = userForm.email
    ElMessage.success('个人信息更新成功')
  } catch (error) {
    ElMessage.error('更新失败')
  }
}

const simulateSmsNotification = () => {
  // 延迟几秒后显示验证码（模拟短信接收时间）
  setTimeout(() => {
    let code = '';
    code = userStore.ssmcode;
    console.log('ssmcode=', userStore.ssmcode)
    ElNotification({
      title: '短信验证码',
      message: `您收到的验证码是: ${code} (此功能仅在开发环境显示)`,
      type: 'info',
      duration: 0, // 不自动关闭
    });
  }, 2000); // 2秒后显示，模拟短信接收时间
}


const handleChangePassword = async () => {
  // 调用API/user/password修改密码
  try {
    // await axios.post('/api/user/password', passwordForm)
    userStore.updatePassword(passwordForm)
    ElMessage.success('密码修改成功')
    passwordForm.oldPassword = ''
    passwordForm.newPassword = ''
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '密码修改失败')
  }
}

const handleUpdatePhone = async () => {
  if (!phoneForm.phone) {
    ElMessage.warning('请输入新手机号')
    return
  }

  if (!phoneForm.code) {
    ElMessage.warning('请输入验证码')
    return
  }

  // 验证手机号格式
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(phoneForm.phone)) {
    ElMessage.error('请输入正确的手机号格式')
    return
  }

  // 验证验证码格式（假设为6位数字）
  const codeRegex = /^\d{6}$/
  if (!codeRegex.test(phoneForm.code)) {
    ElMessage.error('请输入正确的验证码格式')
    return
  }

  try {
    userStore.updatePhone(phoneForm)

    userInfo.phone = phoneForm.phone
    userForm.phone = phoneForm.phone

    // 清空表单
    phoneForm.phone = ''
    phoneForm.code = ''
    stopCountdown()
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '手机号更新失败')
  }
}

const handleSubmitAuth = async () => {
  if (!authForm.agreement) {
    ElMessage.warning('请先同意实名认证协议')
    return
  }

  try {
    // 验证表单
    if (!authForm.realName) {
      ElMessage.warning('请输入真实姓名')
      return
    }

    if (!authForm.idCard) {
      ElMessage.warning('请输入身份证号')
      return
    }

    // 验证身份证号格式
    const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
    if (!idCardRegex.test(authForm.idCard)) {
      ElMessage.error('请输入正确的身份证号')
      return
    }

    userStore.authSubmit(authForm)

    userInfo.authStatus = 1
    ElMessage.success('实名认证已提交，请等待审核')

    // 清空表单
    authForm.realName = ''
    authForm.idCard = ''
    authForm.agreement = false
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '提交失败')
  }
}

const handleResetAuthForm = () => {
  authForm.realName = ''
  authForm.idCard = ''
  authForm.agreement = false
}


/* 管理员操作 */
const handleApproveAuth = async (row) => {
  // 通过审核
  try {
    // 设置认证表单数据
    verifyForm.userId = row.userId;
    verifyForm.status = 2; // 通过认证状态为2
    verifyForm.rejectReason = ''; // 通过认证不需要拒绝原因

    // 调用认证接口
    await userStore.authVerify(verifyForm);

    // 从待审核列表中移除该项
    pendingList.value = pendingList.value.filter(item => item.id !== row.id);

    ElMessage.success('已通过认证');
  } catch (error) {
    console.error('认证通过失败:', error);
    ElMessage.error('操作失败');
  }
}

const handleRejectAuth = async (row) => {
  // 拒绝审核
  try {
    // 这里应该弹出一个输入框让用户填写拒绝原因
    ElMessageBox.prompt('请输入拒绝原因', '确认拒绝', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /\S/,
      inputErrorMessage: '拒绝原因不能为空'
    }).then(({ value }) => {
      // 用户点击确定
      verifyForm.userId = row.userId;
      verifyForm.status = 3; // 拒绝认证状态为3
      verifyForm.rejectReason = value; // 使用用户输入的拒绝原因

      // 调用认证接口
      userStore.authVerify(verifyForm)
          .then(() => {
            // 从待审核列表中移除该项
            pendingList.value = pendingList.value.filter(item => item.id !== row.id);
            ElMessage.success('已拒绝认证');
          })
          .catch((error) => {
            console.error('认证拒绝失败:', error);
            ElMessage.error('操作失败');
          });
    }).catch(() => {
      // 用户点击取消
      ElMessage.info('已取消操作');
    });
  } catch (error) {
    console.error('认证拒绝失败:', error);
    ElMessage.error('操作失败');
  }
}

// 组件销毁时清除定时器
onMounted(() => {
  // 组件销毁前的清理工作
  window.addEventListener('beforeunload', () => {
    if (countdownTimer) {
      clearInterval(countdownTimer)
    }
  })
})
</script>

<template>
  <div class="user-center-container">
    <el-tabs v-model="activeTab" class="user-tabs">
      <!-- 个人信息标签页 -->
      <el-tab-pane label="个人信息" name="profile">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <el-icon>
                <User/>
              </el-icon>
              <span>基本资料</span>
            </div>
          </template>

          <div class="user-info">
            <el-row :gutter="20">
              <el-col :span="4">
                <div class="avatar-container">
                  <el-avatar :src="userInfo.avatar" :size="80"/>
                </div>
              </el-col>
              <el-col :span="20">
                <el-descriptions :column="1" border>
                  <el-descriptions-item label="用户ID">{{ userInfo.userId }}</el-descriptions-item>
                  <el-descriptions-item label="用户名">{{ userInfo.name }}</el-descriptions-item>
                  <el-descriptions-item label="邮箱">{{ userInfo.email }}</el-descriptions-item>
                  <el-descriptions-item label="手机号">{{ userInfo.phone }}</el-descriptions-item>
                  <el-descriptions-item label="用户类型">
                    <el-tag :type="userInfo.userType === 'ADMIN' ? 'danger' : 'primary'">
                      {{ userInfo.userType === 'ADMIN' ? '管理员' : '普通用户' }}
                    </el-tag>
                  </el-descriptions-item>
                </el-descriptions>
              </el-col>
            </el-row>
          </div>

          <el-form
              :model="userForm"
              label-width="100px"
              label-position="top"
              @submit.prevent="handleUpdateProfile"
              style="margin-top: 20px;"
          >
            <el-form-item label="用户名" prop="name">
              <el-input v-model="userForm.name"/>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" type="email"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleUpdateProfile">保存修改</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>

      <!-- 安全设置标签页 -->
      <el-tab-pane label="安全设置" name="security">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <el-icon>
                <Lock/>
              </el-icon>
              <span>密码修改</span>
            </div>
          </template>

          <el-form
              :model="passwordForm"
              :rules="passwordRules"
              label-width="120px"
              label-position="top"
              @submit.prevent="handleChangePassword"
          >
            <el-form-item label="原密码" prop="oldPassword">
              <el-input v-model="passwordForm.oldPassword" type="password" show-password/>
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="passwordForm.newPassword" type="password" show-password/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleChangePassword">确认修改</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <el-card class="box-card" style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <el-icon>
                <Iphone/>
              </el-icon>
              <span>手机绑定</span>
            </div>
          </template>

          <el-form
              :model="phoneForm"
              label-width="100px"
              label-position="top"
              @submit.prevent="handleUpdatePhone"
          >
            <el-form-item label="当前手机号">
              <el-input v-model="userInfo.phone" disabled/>
            </el-form-item>

            <el-form-item label="新手机号">
              <el-input
                  v-model="phoneForm.phone"
                  placeholder="请输入新手机号"
                  maxlength="11"
              />
            </el-form-item>

            <el-form-item label="验证码">
              <div class="verification-code-container">
                <el-input
                    v-model="phoneForm.code"
                    placeholder="请输入验证码"
                    maxlength="6"
                    style="flex: 1; margin-right: 10px;"
                />
                <el-button
                    type="primary"
                    :disabled="isCounting"
                    @click="handleGetVerificationCode"
                >
                  {{ isCounting ? `${countdown}秒后重新获取` : '获取验证码' }}
                </el-button>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleUpdatePhone">更新手机号</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>

      <!-- 实名认证标签页 -->
      <el-tab-pane label="实名认证" name="authentication">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <el-icon>
                <Document/>
              </el-icon>
              <span>实名认证</span>
            </div>
          </template>

          <!-- 认证状态展示 -->
          <div class="auth-status-container">
            <div class="auth-status-header">
              <el-icon :size="24"
                       :color="userInfo.authStatus === 2 ? '#67C23A' :
                          userInfo.authStatus === 1 ? '#E6A23C' :
                          userInfo.authStatus === 3 ? '#F56C6C' : '#909399'">
                <Warning v-if="userInfo.authStatus === 0 || userInfo.authStatus === 3"/>
                <Document v-else/>
              </el-icon>
              <div class="auth-status-text">
                <h3>
                  {{
                    userInfo.authStatus === 0 ? '未认证' :
                        userInfo.authStatus === 1 ? '审核中' :
                            userInfo.authStatus === 2 ? '已认证' : '认证失败'
                  }}
                </h3>
                <p>
                  {{
                    userInfo.authStatus === 0 ? '完成实名认证，享受更多服务' :
                        userInfo.authStatus === 1 ? '我们正在审核您的认证信息，请耐心等待' :
                            userInfo.authStatus === 2 ? '您的身份已通过认证' : '您的认证未通过，请重新提交认证'
                  }}
                </p>
              </div>
            </div>

            <div class="auth-status-tag">
              <el-tag
                  :type="userInfo.authStatus === 0 || userInfo.authStatus === 3 ? 'info' :
                     userInfo.authStatus === 2 ? 'success' : 'warning'"
                  size="large"
              >
                {{
                  userInfo.authStatus === 0 ? '未认证' :
                      userInfo.authStatus === 1 ? '审核中' :
                          userInfo.authStatus === 2 ? '已认证' : '认证失败'
                }}
              </el-tag>
            </div>
          </div>

          <!-- 已认证信息展示 -->
          <div v-if="userInfo.authStatus === 2" class="auth-info-display">
            <el-divider content-position="left">认证信息</el-divider>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="真实姓名">{{ userInfo.authInfo.realName }}</el-descriptions-item>
              <el-descriptions-item label="身份证号">{{ userInfo.authInfo.idCard }}</el-descriptions-item>
              <el-descriptions-item label="认证时间">2023-01-01 12:00:00</el-descriptions-item>
            </el-descriptions>

            <div class="auth-tips">
              <el-alert
                  title="认证信息保护"
                  description="您的实名认证信息已加密存储，仅用于身份验证，不会用于其他用途。"
                  type="info"
                  show-icon
                  :closable="false"
              />
            </div>
          </div>

          <!-- 认证申请表单 -->
          <div v-else>
            <el-alert
                v-if="userInfo.authStatus === 1"
                title="认证审核中"
                description="您的认证申请正在审核中，请耐心等待。审核通过后，您将享受完整的平台服务。"
                type="warning"
                show-icon
                :closable="false"            style="margin-bottom: 20px;"
            />

            <el-alert
                v-if="userInfo.authStatus === 3"
                title="认证失败"
                description="您的认证申请未通过审核，请修改后重新提交。"
                type="error"
                show-icon
                :closable="false"            style="margin-bottom: 20px;"
            />

            <el-form
                :model="authForm"
                :rules="authRules"
                label-width="100px"
                label-position="top"
                @submit.prevent="handleSubmitAuth"
            >
              <el-form-item label="真实姓名" prop="realName">
                <el-input
                    v-model="authForm.realName"
                    :placeholder="userInfo.authStatus === 1 ? '' : '请输入您的真实姓名'"
                    :disabled="userInfo.authStatus === 1"
                    :value="userInfo.authStatus === 1 ? userInfo.authInfo.realName : authForm.realName"
                />
              </el-form-item>

              <el-form-item label="身份证号" prop="idCard">
                <el-input
                    v-model="authForm.idCard"
                    :placeholder="userInfo.authStatus === 1 ? '' : '请输入您的身份证号码'"
                    :disabled="userInfo.authStatus === 1"
                    :value="userInfo.authStatus === 1 ? userInfo.authInfo.idCard : authForm.idCard"
                />
              </el-form-item>

              <el-form-item>
                <el-checkbox
                    v-model="authForm.agreement"
                    :disabled="userInfo.authStatus === 1"
                >
                  我已阅读并同意
                  <el-link type="primary" underline="hover">《实名认证协议》</el-link>
                </el-checkbox>
              </el-form-item>

              <el-form-item>
                <el-button
                    type="primary"
                    @click="handleSubmitAuth"
                    :loading="userInfo.authStatus === 1"
                    :disabled="userInfo.authStatus === 1"
                >
                  {{ userInfo.authStatus === 1 ? '审核中...' : '提交认证' }}
                </el-button>
                <el-button
                    @click="handleResetAuthForm"
                    :disabled="userInfo.authStatus === 1"                style="margin-left: 10px;"
                >
                  重置
                </el-button>
              </el-form-item>
            </el-form>

            <div class="auth-tips">
              <el-alert
                  title="认证说明"
                  description="1. 实名认证后可享受更多平台服务；2. 认证信息仅用于身份验证，严格保密；3. 认证审核通常在1个工作日内完成。"
                  type="info"
                  show-icon
                  :closable="false"
              />
            </div>
          </div>
        </el-card>
      </el-tab-pane>

      <!-- 管理员功能（条件渲染） -->
      <el-tab-pane
          v-if="userInfo.userType === 'ADMIN'"
          label="认证审核"
          name="admin"
      >
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <el-icon>
                <Document/>
              </el-icon>
              <span>认证审核列表</span>
            </div>
          </template>

          <el-table :data="pendingList" style="width: 100%">
            <el-table-column prop="realName" label="姓名"/>
            <el-table-column prop="idCard" label="身份证号"/>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button size="small" type="success" @click="() => handleApproveAuth(scope.row)">
                  <el-icon>
                    <Check/>
                  </el-icon>
                  通过
                </el-button>
                <el-button size="small" type="danger" @click="() => handleRejectAuth(scope.row)">
                  <el-icon>
                    <Close/>
                  </el-icon>
                  拒绝
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div v-if="pendingList.length === 0" style="text-align: center; padding: 20px; color: #999;">
            暂无待审核项
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped>
.user-center-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.user-tabs {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 10px;
}

.el-icon {
  font-size: 18px;
}

.user-info {
  padding: 20px 0;
}

.avatar-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.verification-code-container {
  display: flex;
  align-items: center;
}

.auth-status-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 20px;
}

.auth-status-header {
  display: flex;
  align-items: center;
  gap: 15px;
}

.auth-status-text h3 {
  margin: 0 0 5px 0;
}

.auth-status-text p {
  margin: 0;
  color: #606266;
}

.auth-info-display {
  margin-top: 20px;
}

.auth-tips {
  margin-top: 20px;
}
</style>
